package com.qfedu.meidijiaju.controller;

import com.qfedu.meidijiaju.entity.User;
import com.qfedu.meidijiaju.service.UserService;
import com.qfedu.meidijiaju.common.ResponseData;
import com.qfedu.meidijiaju.utils.AliSmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.qfedu.meidijiaju.common.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Api(tags = "用户表模块接口")
@RestController
public class Usercontroller {
    @Autowired
    private UserService userService;

    private Map<String,Object> map =  new HashMap<String,Object>();

    // 应用重新启动之后 codeMap 会重新创建，数据丢失
    private ConcurrentHashMap<String,String> codeMap = new ConcurrentHashMap<>();

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @ApiOperation(value = "/getCode 获取验证码") // 说明当前接口用来获取验证码
    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public ResponseData<String> getCode(String phone){

        // 1.先得到随机的验证码
        int code = AliSmsUtil.randomNum(6);

        // 2.将手机号 和  验证码保存起来60s
        //   最好是存储到redis 中  key 手机号 value 验证码  保存60s  但是我们还没有学习到
        //   将手机号   验证码    保存到session      但是我们的应用大部分都是app ,session 会话不易保持
        //   将手机号和验证码  保存到  数据库某一数据表中  或者 map  中，  最次的方案
        //   我们暂时保存到 map 中，后续学习redis之后 ，存储到redis 中
        codeMap.put(phone,code+"");

        // 3.将验证码发送到 对应手机中
        AliSmsUtil.sendSmsCode(phone,code+"",AliSmsUtil.SMS_TEM_LOGIN);


        // 4.返回前端 数据请注意查收验证码

        ResponseData<String> responseData = new ResponseData<>();

        responseData.setCode(0);

        responseData.setMsg("success" + code);
        responseData.setData("请注意查收验证码");

        return responseData;
    }

    /**
     * 查询所登录用户的用户名 ， 并放到 session 域
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "登录接口,选中登录方式type(1 手机号密码，2 手机号验证码)，新手机号请需要先注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",required = true),
            @ApiImplicitParam(name = "type",value = "登录类型（1 手机号密码，2 手机号验证码）",allowableValues = "1,2",required = true)
    })
    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    //TODO
    public ResponseData<Map<String,Object>> login(User user,String code,int type) {

        // 登录方式
        // 手机号验证码登录

        if (type == 1) {
            // 1.获取到手机号 对应的验证码，进行比较
            // 后台产生的验证码
            String realCode = codeMap.get(user.getPhone());
            ResponseData<Map<String,Object>> responseData = new ResponseData<>();
            System.out.println("realCode = " + realCode);

            //查询当前手机号对应用户是否存在
            User result = userService.queryUserInfoByPhone(user.getPhone());

            if (realCode.equals(code) && result != null) { // 验证码成功
                // 完成登录相关业务
                map.put("currentUser",result);
                responseData.setCode(0);
                responseData.setMsg("登录成功");
                responseData.setData(map);
            }
            else { // 登录失败
                responseData.setMsg("手机号或验证码错误或该用户不存在需先注册");
                responseData.setCode(1);
            }

            return responseData;
        }

        //账号密码登录

        //将 User数据放到全局变量 map 中
        User result = userService.login(user);

        map.put("currentUser",result);

        ResponseData<Map<String,Object>> responseData = new ResponseData<>();
        if (result != null) {// 成功
            responseData.setMsg("登录成功");
            responseData.setCode(0);
            responseData.setData(map);
        } else { // 登录失败
            responseData.setMsg("手机号或密码错误");
            responseData.setCode(1);
        }

        return responseData;
    }

    /**
     * 个人主页下的编辑资料按钮 查询当前用户全部信息
     *
     * @param name 前端传递一个 String name
     * @return ResponseData<User>
     */
    @ApiOperation("查询用户信息接口")
    @RequestMapping(value = "/user/queryUserInfo",method = RequestMethod.GET)
    public ResponseData<User> queryUserInfo(String name) {

        User user = userService.queryUserInfo(name);
        ResponseData<User> responseData = new ResponseData<>();

        responseData.setData(user);



        return responseData;
    }

    /**
     * 修改用户信息，根据用户 id
     * @param user
     * @return
     */
    @ApiOperation("更改用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true)

    })
    @RequestMapping(value = "/user/updateUserInfo", method = RequestMethod.GET)
    public ResponseData<String> updateUserInfo(User user,String code) {
        ResponseData<String> responseData = new ResponseData<>();

        // 判断修改数据中是否带有密码
        if (user.getPassword() != null || user.getPhone() != null) {  // 修改数据中带有密码
            User currentUser =(User) map.get("currentUser");

            // 判断用户获取验证码手机号是否是注册时手机号
            if (!user.getPhone().equals(currentUser.getPhone())) {
                responseData.setMsg("该手机号非用户注册手机号");
                return responseData;
            }

            String realCode = codeMap.get(user.getPhone());
            System.out.println("realCode = " + realCode);

            if (realCode == null) {
                responseData.setMsg("请先获取验证码");
                return responseData;
            }
            if (realCode.equals(code)) {
                User userInfo = userService.queryUserInfoByPhone(user.getPhone());

                boolean result = userService.updateUserInfo(user);
                if (result) {
                    responseData.setMsg("修改成功");
                    responseData.setCode(0);
                } else {
                    responseData.setMsg("修改失败");
                    responseData.setCode(1);
                }

                return responseData;
            }
        }

        // 修改数据不带有密码
        // 获取用户id ，赋值到前端传入 user

        boolean result = userService.updateUserInfo(user);
        if (result) {
           responseData.setMsg("修改成功");
           responseData.setCode(0);
        } else {
            responseData.setMsg("修改失败");
            responseData.setCode(1);
        }

        return responseData;
    }

    /**
     * 退出登录
     * @param id
     * @return
     */
    @ApiOperation("退出登录接口")
    @RequestMapping(value = "/user/logOut",method = RequestMethod.GET)
    public ResponseData<String> logOut(int id) {
        map.clear();
        ResponseData<String> responseData = new ResponseData<>();
        if (map.isEmpty()) {
            responseData.setCode(0);
            responseData.setMsg("退出成功");
        }

        return responseData;
    }

    /**
     * 注销用户
     * @param id
     * @return
     */
    @ApiOperation("注销接口")
    @RequestMapping(value = "/user/deleteUser",method = RequestMethod.GET)
    public ResponseData<String> deleteUser(int id) {

        ResponseData<String> responseData = new ResponseData<>();
        boolean result = userService.deleteUser(id);

        if (result) {
            responseData.setCode(0);
            responseData.setMsg("注销成功");
        }

        return responseData;
    }

    /**
     * 注册用户
     * @param user
     * @param code
     * @return
     */
    @ApiOperation("注册用户接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",required = true),
            @ApiImplicitParam(name = "code",required = true)
    })
    @RequestMapping(value = "/user/register",method = RequestMethod.GET)
    public ResponseData<String> register(User user,String code) {
        String realCode = codeMap.get(user.getPhone());
        ResponseData<String> responseData = new ResponseData<>();
        System.out.println("realCode = " + realCode);

        if (realCode == null) {
            responseData.setMsg("请先获取验证码");
            return responseData;
        }
        // 判断验证码是否正确
        if (realCode.equals(code)) {
            User userInfo = userService.queryUserInfoByPhone(user.getPhone());
            if (userInfo == null) {  //如果没有该手机号
                // 默认用户名为注册手机号
                if (user.getName() == null) {
                    user.setName(user.getPhone());
                }
                if (user.getPassword() == null) {

                    // 初始密码为注册手机号
                    user.setPassword(user.getPhone());
                }
                if (user.getImg() == null) {
                    //设置初始头像
                    user.setImg("https://java2211.oss-cn-beijing.aliyuncs.com/avatar16.png?Expires=1697449292&OSSAccessKeyId=LTAIdN2LGhwk7nKd&Signature=wWkgbez78NSOdzsGuDQ8BGw00UA%3D");
                }

                boolean result = userService.register(user);
                if (result) {
                    responseData.setCode(0);
                    responseData.setMsg("注册成功");
                }
            } else {
                responseData.setCode(1);
                responseData.setMsg("该手机号已存在");
            }
        } else {
            responseData.setCode(1);
            responseData.setMsg("验证码不正确");
        }


        return responseData;
    }

    @ApiOperation("查询所有用户信息")
    @RequestMapping(value = "/user/queryAllUser",method = RequestMethod.GET)
    public ResponseData<List<User>> queryAllUser() {
        ResponseData<List<User>> responseData = new ResponseData<>();
        List<User> result = userService.queryAllUser();

        if (result != null) {
            responseData.setCode(0);
            responseData.setMsg("查询成功");
            responseData.setData(result);
        }

        return responseData;
    }


}
